package com.xuecheng.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.learning.feignclient.ContentServiceClient;
import com.xuecheng.learning.mapper.XcChooseCourseMapper;
import com.xuecheng.learning.mapper.XcCourseTablesMapper;
import com.xuecheng.learning.model.dto.XcChooseCourseDto;
import com.xuecheng.learning.model.dto.XcCourseTablesDto;
import com.xuecheng.learning.model.po.XcChooseCourse;
import com.xuecheng.learning.model.po.XcCourseTables;
import com.xuecheng.learning.service.MyCourseTableService;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;


@Slf4j
@Service
public class MyCourseTableServiceImpl implements MyCourseTableService {
    /**
     * 选课相关接口实现
     * @param userId
     * @param courseId
     * @return
     */
    @Autowired
    XcChooseCourseMapper chooseCourseMapper;
    @Autowired
    XcCourseTablesMapper courseTablesMapper;
    @Autowired
    ContentServiceClient contentServiceClient;

    @Transactional
    @Override
    public XcChooseCourseDto addChooseCourse(String userId, Long courseId){
      //远程调用内容管理查询课程的收费规则
      CoursePublish coursepublish = contentServiceClient.getCoursepublish(courseId);
      if(coursepublish == null){
          XueChengPlusException.cast("课程不存在");
      }
      String charge = coursepublish.getCharge();
      XcChooseCourse chooseCourse = null;
      if("201000".equals(charge)){
          //如果免费课程，会向课程记录表、我的课程表数据
          chooseCourse = addFreeCourse(userId, coursepublish);
          XcCourseTables courseTables = addCourseTables(chooseCourse);
      }else {
          //如果收费课程，会像选课记录表写数据
          chooseCourse = addChargeCourse(userId, coursepublish);
      }
      //判断学生的学习资格
      XcCourseTablesDto xcCourseTablesDto = getLearningsStatus(userId, courseId);
      XcChooseCourseDto xcChooseCourseDto = new XcChooseCourseDto();
      BeanUtils.copyProperties(chooseCourse, xcChooseCourseDto);
      xcChooseCourseDto.setLearnStatus(xcCourseTablesDto.getLearnStatus());
      return xcChooseCourseDto;
    }

    //添加免费课程，免费课程加入选课记录表
    public XcChooseCourse addFreeCourse(String userId, CoursePublish coursePublish){
        Long courseId = coursePublish.getId();
        LambdaQueryWrapper<XcChooseCourse> queryWrapper = new LambdaQueryWrapper<XcChooseCourse>().eq(XcChooseCourse::getUserId,userId)
                .eq(XcChooseCourse::getCourseId,courseId)
                .eq(XcChooseCourse::getOrderType,"700001")
                .eq(XcChooseCourse::getStatus,701001);
        List<XcChooseCourse> xcChooseCourses = chooseCourseMapper.selectList(queryWrapper);
        if(xcChooseCourses.size()>0){
            return xcChooseCourses.get(0);
        }
        //向选课记录表写数据
        XcChooseCourse chooseCourse = new XcChooseCourse();
        chooseCourse.setCourseId(courseId);
        chooseCourse.setCourseName(coursePublish.getName());
        chooseCourse.setUserId(userId);
        chooseCourse.setCompanyId(coursePublish.getCompanyId());
        chooseCourse.setOrderType("700001");
        chooseCourse.setCreateDate(LocalDateTime.now());
        chooseCourse.setCoursePrice(coursePublish.getPrice());
        chooseCourse.setValidDays(365);
        chooseCourse.setStatus("701001");
        chooseCourse.setValidtimeStart(LocalDateTime.now());
        chooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(365));

        int insert = chooseCourseMapper.insert(chooseCourse);
        if(insert<=0){
            XueChengPlusException.cast("添加选课记录失败");
        }
        return chooseCourse;
    }

    //添加到我的课程表
    public XcCourseTables addCourseTables(XcChooseCourse xcChooseCourse){
        String status = xcChooseCourse.getStatus();
        if(!"701001".equals(status)){
            XueChengPlusException.cast("选课没有成功无法添加到课程表");
        }
        XcCourseTables xcCourseTables = getXcCourseTables(xcChooseCourse.getUserId(),xcChooseCourse.getCourseId());
        if(xcCourseTables != null){
            return xcCourseTables;
        }
        xcCourseTables = new XcCourseTables();
        BeanUtils.copyProperties(xcChooseCourse,xcCourseTables);
        xcCourseTables.setChooseCourseId(xcChooseCourse.getId());//记录选课表中的主键
        xcCourseTables.setCourseType(xcChooseCourse.getOrderType());//选课类型
        xcCourseTables.setUpdateDate(LocalDateTime.now());
        int insert = courseTablesMapper.insert(xcCourseTables);
        if(insert<=0){
            XueChengPlusException.cast("添加我的课程表失败");
        }

        return xcCourseTables;
    }

    //添加收费课程
    public XcChooseCourse addChargeCourse(String userId, CoursePublish coursePublish){
        Long courseId = coursePublish.getId();
        //判断，如果存在收费的选课记录，且选课状态为待支付，直接返回
        LambdaQueryWrapper<XcChooseCourse> queryWrapper = new LambdaQueryWrapper<XcChooseCourse>().eq(XcChooseCourse::getUserId,userId)
                .eq(XcChooseCourse::getCourseId,courseId)
                .eq(XcChooseCourse::getOrderType,"700002")
                .eq(XcChooseCourse::getStatus,701002);
        List<XcChooseCourse> xcChooseCourses = chooseCourseMapper.selectList(queryWrapper);
        if(xcChooseCourses.size()>0){
            return xcChooseCourses.get(0);
        }
        //向选课记录表写数据
        XcChooseCourse chooseCourse = new XcChooseCourse();
        chooseCourse.setCourseId(courseId);
        chooseCourse.setCourseName(coursePublish.getName());
        chooseCourse.setUserId(userId);
        chooseCourse.setCompanyId(coursePublish.getCompanyId());
        chooseCourse.setOrderType("700002");
        chooseCourse.setCreateDate(LocalDateTime.now());
        chooseCourse.setCoursePrice(coursePublish.getPrice());
        chooseCourse.setValidDays(365);
        chooseCourse.setStatus("701002");
        chooseCourse.setValidtimeStart(LocalDateTime.now());
        chooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(365));

        int insert = chooseCourseMapper.insert(chooseCourse);
        if(insert<=0){
            XueChengPlusException.cast("添加选课记录失败");
        }
        return chooseCourse;
    }
    //根据课程和用户查询我的课程表中某一门课程

    public XcCourseTables getXcCourseTables(String userId, Long courseId){
        XcCourseTables xcCourseTables = courseTablesMapper.selectOne(
                new LambdaQueryWrapper<XcCourseTables>().eq(XcCourseTables::getCourseId,courseId)
                        .eq(XcCourseTables::getUserId,userId)
        );
        return xcCourseTables;
    }

    //查询学习资格
    @Override
    public XcCourseTablesDto getLearningsStatus(String userId, Long courseId){
        //查询我的课程表,如果查不到说明没有选课
        XcCourseTablesDto courseTablesDto = new XcCourseTablesDto();
        XcCourseTables xcCourseTables = getXcCourseTables(userId, courseId);
        if(xcCourseTables == null){
            courseTablesDto.setLearnStatus("702002");
            return courseTablesDto;
        }
        //如果查到了，判断是否过期，如果过期不能继续学习，没有过期可以继续学习
        boolean before = xcCourseTables.getValidtimeEnd().isBefore(LocalDateTime.now());
        if(before){
            courseTablesDto.setLearnStatus("702003");
            BeanUtils.copyProperties(xcCourseTables, courseTablesDto);
            return courseTablesDto;
        }else{
            courseTablesDto.setLearnStatus("702001");
            BeanUtils.copyProperties(xcCourseTables, courseTablesDto);
            return courseTablesDto;
        }
    }

    @Override
    @Transactional
    public boolean saveChooseCourseSuccess(String chooseCourseId){
        // 根据选课id查询选课表
        XcChooseCourse chooseCourse = chooseCourseMapper.selectById(chooseCourseId);
        if(chooseCourse == null){
            log.debug("接收购买课程的消息，根据选课id从数据库找不到选课记录:{}", chooseCourseId);
            return false;
        }
        // 选课状态
        String status = chooseCourse.getStatus();
        //只有当未支付时才更新为已支付
        if("701002".equals(status)){
            //更新选课记录的状态为支付成功
            chooseCourse.setStatus("701001");
            //向我的课程表插入记录
            int i = chooseCourseMapper.updateById(chooseCourse);
            if(i<=0){
                log.debug("添加选课记录失败:{}",chooseCourse);
                XueChengPlusException.cast("添加选课记录失败");
            }
            //向我的课程表插入记录
            XcCourseTables xcCourseTables = addCourseTables(chooseCourse);

        }
        return true;
    }
}
